from fontTools.ttLib.woff2 import main
import requests
import re
from fontTools.ttLib import TTFont
from PIL import Image, ImageDraw, ImageFont
from requests.api import head
import pytesseract
import numpy


headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.80 Safari/537.36 Edg/86.0.622.43',
    'cookies': '',
    "Connection": "keep-alive",
    "Upgrade-Insecure-Requests": "1",
    "Host": "www.dianping.com",
}
url = 'https://www.dianping.com/hangzhou/ch10'

html = requests.get(url, headers=headers)
print(html.status_code)

# 获取cssurl
def get_cssurl(html):
    css_re = re.compile(r'([^"]+svgtextcss[^"]+)')
    css_url = re.search(css_re, html.text).group(0)
    css_url = 'http:' + css_url
    return css_url

# 获取woffurl,下载woff文件
def get_woffurl(css_url):
    svg_text = requests.get(css_url).text
    woff_re = re.compile('PingFangSC-Regular-shopNum.*url\(\"(\/\/s3plus\.meituan\.net\/v1.*?.woff).*shopNum')
    woff_url = re.findall(woff_re, svg_text).group[0]
    woff_url = 'http:' + woff_url
    woff = requests.get(woff_url).content
    woff_name = re.findall(r'font/(.*?).woff', woff_url)[0]
    woff_path = './dazhongdp/woff/' + '{}.woff' .formatz(woff_name)
    with open('woff_path', 'wb')as f:
        f.write(woff)

    font = TTFont(woff_path)
    font_path = './woff/' + '{}.xml'.format(woff_name)
    font.saveXML(font_path)
    print('字体文件已下载转换，正在生成图片并OCR...')
    return font, woff_path

def font_convert():
    codelist = font.getGlyphOrder()[2:]
    im = Image.new('RGB', (1800,1000), (255,255,255))
    dr = ImageDraw.Draw(im)
    font = ImageFont.truetype(woff_path, 40)
    count = 15
    font_split = numpy.array_spilt(countlist, count)
    for t in range(count):
        new_font_split = [i.replace('uni', '\\u') for i in font_split[i]]
        text = ''.join(new_font_split)
        text = text.encode('utf-8').decode('unicode_escape')
        dr.text((0, 50 * t), text, font=font, fill='#00000')
    res = pytesseract.image_to_string(im, lang='chi_sim')
    res = res.replace(' ', '').replace('\n', '')
    codelist = [i.replace('uni', '&#x') + ';' for i in codelist]
    print('完成')
    return dict(zip(codelist,list(res)))


if __name__ == "__main__":
    svg_url = get_cssurl(html)
    font, woff_path = get_woffurl(svg_url)
    font_convert()

